package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.util.List;
import java.util.Set;

/**
 * 分类管理
 */
@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DataSource dataSource;

    /**
     * 添加分类
     */
    @PostMapping
    @CacheEvict(cacheNames = "category", allEntries = true)
    public R<String> save(@RequestBody Category category) {
        //调用业务层
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("page")
    public R<Page<Category>> page(Integer page, Integer pageSize) {

        Page<Category> pageInfo = new Page<>(page, pageSize);

        //调用业务层
        categoryService.lambdaQuery()
                .orderByAsc(Category::getSort) //排序字段
                .orderByDesc(Category::getUpdateTime) //排序字段
                .page(pageInfo); //分页查询

        return R.success(pageInfo);
    }


    /**
     * 根据id删除
     */
    @DeleteMapping
    @CacheEvict(cacheNames = "category", allEntries = true)
    public R<String> deleteById(Long id) {
        //调用业务层
        categoryService.deleteById(id);
        return R.success("删除成功");
    }

    /**
     * 更新分类信息
     */
    @PutMapping
    @CacheEvict(cacheNames = "category", allEntries = true)
    public R<String> update(@RequestBody Category category) {
        //调用业务层
        categoryService.updateById(category);
        return R.success("修改成功....");
    }

    /**
     * 根据type查询分类列表
     *
     * @Cacheable：
     *      cacheNames属性：表示存入redis中的key的一部分（前缀）
     *      key属性：表示存入redis中的key的一部分
     *      redis完整的key=cacheNames + key
     */
    @GetMapping("list")
    @Cacheable(cacheNames = "category", key = "''+ #type")
    public R<List<Category>> list(Integer type) {
        //select * from category where type=1
        List<Category> list = categoryService.lambdaQuery()
                .eq(type != null, Category::getType, type) //条件，必须要对type进行非空判断，否则将来移动端首页不展示首页分类数据
                .orderByAsc(Category::getSort) //排序
                .list(); //查所有
        return R.success(list);
    }
}
